import type { RouteRecordRaw } from 'vue-router'
function loadLocalRoutes() {
  // ○ 动态获取所有的路由对象，放到数组中
  const localRoutes: RouteRecordRaw[] = []
  // ■ 目前路由对象都在独立的文件中
  // ■ 从文件中将所有的路由对象读取到数组中
  // ● 读取router/main所有的.ts文件
  const files: Record<string, any> = import.meta.glob('@/router/main/**/*.ts', {
    eager: true
  })
  // 将加载的对象放到localRoutes数组中
  for (const key in files) {
    localRoutes.push(files[key].default)
  }

  return localRoutes
}
export let firstMenu: any = null
export function mapMenusToRoutes(userMenu: any[]) {
  const localRoutes = loadLocalRoutes()
  // 根据菜单去匹配正确的路由
  const routes: RouteRecordRaw[] = []
  for (const menu of userMenu) {
    for (const submenu of menu.children) {
      const route = localRoutes.find((item) => item.path === submenu.url)
      // 只负责map映射
      if (route) {
        // 给route顶级菜单重定向路由
        if (!routes.find((item) => item.path === menu.url)) {
          routes.push({ path: menu.url, redirect: route.path })
        }
        routes.push(route)
      }
      // if (route) router.addRoute('main', route)
      // 记录第一个被匹配到的菜单
      if (!firstMenu && route) firstMenu = submenu
    }
  }
  return routes
}
/**
 * 根据路径去匹配需要显示的菜单
 * @param userMenu 所有菜单
 * @param path 需要匹配的路径
 */
export function mapRouteToMenu(userMenu: any[], path: string) {
  for (const menu of userMenu) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        return submenu
      }
    }
  }
}
interface IBreadCrumb {
  name: string
  path: string
}
export function mapPathToMenuForBreadCrumb(userMenu: any[], path: string) {
  // 定义面包屑
  const breadcrumb: IBreadCrumb[] = []
  // 获取面包屑的层级
  for (const menu of userMenu) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        breadcrumb.push({ name: menu.name, path: menu.url })
        breadcrumb.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  return breadcrumb
}
